package br.com.projeto.dao;

import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import br.com.projeto.model.Jogo;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

	private final static String TAG = DatabaseHelper.class.getSimpleName();

	private static final String DATABASE_NAME = "megasena.db";
	private static final int DATABASE_VERSION = 1;

	private static DatabaseHelper databaseHelper = null;
	private CadastrarDAO cadastrarDao = null;

	private static final AtomicInteger usageCounter = new AtomicInteger(0);

	public DatabaseHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	public static synchronized DatabaseHelper getHelper(Context context) {
		if (databaseHelper == null) {
			databaseHelper = new DatabaseHelper(context);
		}
		usageCounter.incrementAndGet();
		return databaseHelper;
	}

	@Override
	public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
		try {
			TableUtils.createTableIfNotExists(connectionSource, Jogo.class);
			Log.i(TAG, "Create table with success!");
		} catch (java.sql.SQLException e) {
			Log.e(TAG, "Error to create table: " + e);
			throw new RuntimeException(e);
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
		try {
			TableUtils.dropTable(connectionSource, Jogo.class, true);
			onCreate(sqLiteDatabase);
		} catch (Exception e) {
			Log.e(TAG, "Error to update table: " + e);
			throw new RuntimeException(e);
		}
	}

	public CadastrarDAO getCadastroDao() {
		try {
			if (cadastrarDao == null) {
				cadastrarDao = new CadastrarDAO(connectionSource, Jogo.class);
			}
		} catch (java.sql.SQLException e) {
			Log.e(TAG, "Error to get cadastroDAO: ", e);
		}
		return cadastrarDao;
	}

	@Override
	public void close() {
		super.close();
		cadastrarDao = null;
		databaseHelper = null;
	}
}
